<script setup>
import { computed, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { ElPagination } from 'element-plus';
import { ElButton } from 'element-plus'
import axios from "axios";
import router from "@/router/index.js";

const store = useStore()
//状态
const departments = ref([]); // 部门列表
const positions = ref([]); // 职位列表

//添加弹窗是否开启
const dialogFormVisible = ref(false);
//修改页面的弹窗是否开启
const xiugaiVisible = ref(false);
// 来显示搜索框和原数据框的显示和隐藏
let isShow = ref(true);
//搜索关键字
let searchAll = ref("");

//定义对象数组
const announcementList = computed(()=>{
  return store.state.announcements;
})
// -----------------------------------------

const currentPage = ref(1); // 当前页码 默认是1
const pageSize = ref(5); // 每页显示的条目数  默认是5
const totalItems = computed(()=> announcementList.value.length); // 总条目数，employeelist已经初始化
// 当前页的条目数据
const itemsArr = computed(()=> announcementList.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
))
// -----------------------------------------
//查找功能
const filteremployeelist = computed(() =>
    //filter接受一个回调函数作为参数，并返回一个新数组，该数组包含所有使得回调函数返回true的元素
    announcementList.value.filter(
        (data) =>
            !searchAll.value ||
            String(data.announcementId).includes(String(searchAll.value)) ||
            data.content.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.releaseTime.toLowerCase().includes(searchAll.value.toLowerCase()) ||
            data.title.toLowerCase().includes(searchAll.value.toLowerCase())
    )
)
// 点击搜索
const serchBtn = function () {
  isShow.value = false;
}
//重置
const resetSerchbtn =function () {
  isShow.value = true;
  searchAll.value = "";
}
// =====================================================
const formLabelWidth = '140px';

let form2 = ref({
  announcementId:"",
  title: "",
  content: "",
  releaseTime: "",
})

//=============================
// 封装方法
const sendIndexofId = function (announcementId) {
  for (let i = 0; i < announcementList.value.length; i++) {
    if (announcementId === announcementList.value[i].announcementId) {
      return i;
    }
  }
}
const panduanId = function () {
  //假设不存在
  let idcunzai = false;
  //判断id是否已存在,如果已存在,那么就不添加
  for (let i = 0; i < announcementList.value.length; i++) {
    if (form2.value.announcementId == announcementList.value[i].announcementId) {
      idcunzai = true;
    }
  }
  return idcunzai;
}
//传入一个对象, 如果有这个对象中至少存在一个空字符串,那么就返回true
const hasEmptyString = function (obj) {
  return Object.values(obj).some(value => value === '');
}

//=============================

//进入添加页面   每次进入添加页面都需要向后端发送请求  获取职位和部门数据
const toAddPage = function () {
  dialogFormVisible.value = true;//显示添加页面
  form2.value = {//重置
    announcementId: "",
    title: "",
    content: "",
    releaseTime: "",
  }
  console.log("准备获取部门")
}
//   ----------------------  点击事件确认添加----------------------------
const addEmployee = function () {
  //先判断是否有空输入框
  if (form2.value.title === "" || form2.value.content === ""){
    open2("有空字符串");  //有空字符串   失败
  }else{
    let user = JSON.parse(sessionStorage.getItem("user"));
    console.log("咨询师id",user.consultantId);
      //向数据库发送响应
      axios.post("/announcement", {
        consultantId: user.consultantId,
        title: form2.value.title,
        content: form2.value.content
      }, {
        headers:{"Content-Type":"application/x-www-form-urlencoded"}//键值对结构
      })
          .then(res => {
            console.log(res.data);
            if (res.data.code === 200){
              pushAnnouncement();
              open("添加成功");
            }else{
              open2("添加失败");
            }
          })
          .catch(err=> {
            console.log(err);
          })
      dialogFormVisible.value = false;
  }
}

//===============================

let chushiid = 0;
//进入修改页面
const handleEdit = (announcementId) => {
  //显示修改页面
  xiugaiVisible.value = true;
  chushiid = announcementId;
  console.log("修改页面所传id为:" + chushiid);
  let changeIndex = sendIndexofId(announcementId);  //返回下标,通过下标获取对象
  console.log("修改页面所传index为:" + changeIndex);
  
  //每次点完就传一个下标,根据下标从vuex中取得对象,取完后进行修改再将此对象进行删除后添加
  form2.value = {
    announcementId: store.state.announcements[changeIndex].announcementId,
    title: store.state.announcements[changeIndex].title,
    content: store.state.announcements[changeIndex].content,
  }
  console.log(form2.value)
}

//确认修改 按钮事件
const EditUser = function () {
  //先判断是否有空输入框
  if (form2.value.title === "" || form2.value.content === ""){
    open2("有空字符串");  //  有空字符串 失败
  }else{
    let user = JSON.parse(sessionStorage.getItem("user"));
    console.log("咨询师id",user.consultantId);
      //向数据库发送响应
      axios.put("/announcement", {
        announcementId: form2.value.announcementId,
        title: form2.value.title,  //往数据库中添加的是图片名
        content: form2.value.content,
      })
      .then(res => {
        console.log(res.data);
        if (res.data.code === 200){
          //重新获取数据
          pushAnnouncement();
          open("修改成功"); //修改成功
        }else{
          open2("修改失败");//修改失败
        }
      })
      .catch(err=>{
        console.log(err);
      })
    }

  //关闭修改页面
  xiugaiVisible.value = false;

}

//分页逻辑处理
//==================================================
const handleSizeChange = (s) => {
  pageSize.value = s;
};
//点击事件:更改所要显示的页面
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};
//==================================================
//删除
const handleDelete = (announcementId) => {
  //进行数据库的删除,删除成功后删除vuex中的数据
  axios.delete('/announcement', { params: {id: announcementId } })
      .then(res=>{
        let r = res.data;
        if (r.code === 200){ //数据库删除成功
          //重新获取数据
          pushAnnouncement();
          open("删除成功");
        }else{
          open2("数据库删除失败");//数据库删除失败
        }
        console.log(r.data);
      }).catch(err=>{
    console.error('删除过程中发生错误:', err);
  })
}
//成功
const open = (msg) => {
  ElMessage({
    message: msg,
    type: 'success',
  })
}
//失败
const open2 = (msg) => {
  ElMessage.error(msg);
}


//============================================


// 文件输入框的引用
const fileInput = ref(null);
//封装函数   获取公告的数据
const pushAnnouncement = function (){
  let user = JSON.parse(sessionStorage.getItem('user'));
  // 获取公告数据
  axios.get('/announcement/selectByConsultantId',{
    params:{
      consultantId:user.consultantId
    }
  })
      .then(res=>{
        console.log(res.data.data)
        if (res.data.code === 200){
          //传递到vuex
          store.state.announcements = res.data.data;
        }
      }).catch(err=>{
    console.error(err);
  })
}
//页面显示
onMounted(()=>{
  pushAnnouncement();
})
</script>

<template>
  <ul style="display: flex;justify-content: space-between;padding: 5px">
    <li>
      <!--      进入添加页面-->
      <el-button plain @click="toAddPage">
        添加
      </el-button>
    </li>
    <li style="width: 420px">
      <input style="height: 32.5px;width: 250px;box-sizing: border-box;padding: 5px 10px;border-radius: 5px;border: none" type="text" v-model="searchAll">
      <el-button @click="serchBtn" style="margin-left: 10px">
        🔍搜索
      </el-button>
      <el-button @click="resetSerchbtn">
        重置
      </el-button>
    </li>
  </ul>
  <ul>
    <li>
      <!--    展示  添加  -->
      <!--      新的-------  -->
      <el-dialog v-model="dialogFormVisible" title="发布新公告" width="500" center>
        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="form2"
            label-width="auto"
            class="demo-ruleForm"
            status-icon
        >

          <el-form-item label="标题" prop="content">
            <el-input v-model="form2.title" placeholder="请输入标题" />
          </el-form-item>

          <el-form-item label="内容" prop="releaseTime">
            <el-input v-model="form2.content" placeholder="请输入需要发布的内容" class="tall-input"  type="textarea" id="textarea-style" />
          </el-form-item>
          
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addEmployee">
              确认添加
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!--    修改页面 -->
      <!--      新的-------  -->
      <el-dialog v-model="xiugaiVisible" title="修改公告" width="500" center>
        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="form2"
            label-width="auto"
            class="demo-ruleForm"
            status-icon
        >
          <el-form-item label="标题" prop="content">
            <el-input v-model="form2.title" placeholder="请输入标题" />
          </el-form-item>

          <el-form-item label="内容" prop="releaseTime">
            <el-input v-model="form2.content" placeholder="请输入需要发布的内容" class="tall-input"  type="textarea" id="textarea-style" />
          </el-form-item>
          
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="xiugaiVisible = false">取消</el-button>
            <el-button type="primary" @click="EditUser">
              确认修改
            </el-button>
          </div>
        </template>

      </el-dialog>
    </li>

    <li>

      <!--      当前显示页面    -->
      <el-table v-if="isShow" :data="itemsArr" style="width: 99%">
        <el-table-column prop="announcementId" label="Id" width="50px" />
        <el-table-column prop="title" label="标题" width="220px" />
        <el-table-column prop="content" label="内容" width="320px" />
        <el-table-column prop="releaseTime" label="发布时间" width="170px" />

        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row.announcementId)">
              修改
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.announcementId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--      查找模块   -->
      <el-table v-else :data="filteremployeelist" style="width: 99%">
        <el-table-column prop="announcementId" label="Id" width="50px" />
        <el-table-column prop="title" label="标题" width="220px" />
        <el-table-column prop="content" label="内容" width="320px" />
        <el-table-column prop="releaseTime" label="发布时间" width="170px" />
        <el-table-column align="right">
          <template #header>
            <p>用户操作</p>
          </template>
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row.announcementId)">
              修改
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.announcementId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </li>
    <li>
      <el-pagination v-if="isShow"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[3, 5]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="totalItems">
      </el-pagination>
      <p v-else></p>
    </li>
  </ul>
</template>

<style scoped>

label {
  margin-right: 10px;
}

select {
  margin-bottom: 10px;
  padding: 5px;
}

:deep(.tall-input) {
  height: 300px;
}

:deep(#textarea-style) {
  white-space: normal; /* 根据实际情况选择合适的white-space值，这里normal便于自动换行 */
  overflow: auto; /* 出现滚动条方便查看超出内容 */
  max-height: 300px; /* 限制最大高度，防止内容过多无限拉长组件，可按需调整 */
  line-height: 1.5; /* 设置行高，优化文本显示的美观度，可根据喜好调整 */
}
</style>